package lxthinkingdatas

import (
	"errors"
	"fmt"
	"gitee.com/lxgow/lxconv"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
	"strings"
)

// 数数
// 创建时间:2024/1/17 16:31
// 创建人:lixu

type MQueryConfig struct {
	ApiUrl         string
	SQL            string // 查询密钥
	Token          string // 查询的 SQL 语句
	Format         string //行数据格式默认 json (json,csv,csv_header,tsv,tsv_header,json_object）
	TimeOutSeconds int    //请求超时参数，超时则取消查询任务
}

type MQueryResp struct {
	BodyByte []byte
}

const (
	DEFAULT_FORMAT  = "csv"
	DEFAULT_TIMEOUT = 10
)

func getConfig(config *MQueryConfig) {

	if config.Format == "" {
		config.Format = DEFAULT_FORMAT
	}

	if config.TimeOutSeconds == 0 {
		config.TimeOutSeconds = DEFAULT_TIMEOUT
	}

	if config.Token == "" {
		config.Token = beego.AppConfig.String("thinkingdata::token")
	}

	if config.ApiUrl == "" {
		config.ApiUrl = beego.AppConfig.String("thinkingdata::url")
	}

}

// QuerySql 查询
func QuerySql(config MQueryConfig) (info MQueryResp, err error) {

	getConfig(&config)

	if config.Token == "" || config.ApiUrl == "" {
		err = errors.New("Token or ApiUrl Empty")
		return
	}

	config.ApiUrl = strings.Replace(config.ApiUrl, "https://", "http://", -1)

	apiUrl := config.ApiUrl + "/querySql?token=" + config.Token + "&format=" + config.Format + "&timeoutSeconds=" + fmt.Sprintf("%d", config.TimeOutSeconds) + "&sql=" + lxconv.UrlEncode(config.SQL)

	method := "POST"

	payload := strings.NewReader("")

	client := &http.Client{}

	var (
		req *http.Request
		res *http.Response
	)

	req, err = http.NewRequest(method, apiUrl, payload)
	if err != nil {
		err = fmt.Errorf("http.NewRequest", err.Error())
		return
	}

	req.Header.Add("User-Agent", "Puchi/1.0.0 (https://www.d3games.com)")

	res, err = client.Do(req)
	if err != nil {
		err = fmt.Errorf(" client.Do", err.Error())
		return
	}

	defer res.Body.Close()

	info.BodyByte, err = ioutil.ReadAll(res.Body)
	if err != nil {
		err = fmt.Errorf(" ioutil.ReadAll", err.Error())
		return
	}

	return
}
